package com.it.myd.websocket.socket.wuziqi;

import com.it.myd.bean.box.UserGameInfo;
import com.it.myd.bean.box.game.Room;
import com.it.myd.bean.main.ReturnValue;
import com.it.myd.bean.main.User;
import com.it.myd.controller.main.module.WuZiQiController;
import com.it.myd.service.main.module.room.RoomService;
import com.it.myd.service.main.module.wuziqi.WuZiQiService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class WuziqiMatchWebSocket extends TextWebSocketHandler {

    @Autowired
    WuZiQiController wuZiQiController;
    @Autowired
    RoomService roomService;
    @Autowired
    WuZiQiService wuZiQiService;

    private Map<WebSocketSession,Map<String,String>> userMap = new HashMap<>();
    private Map<String, List<WebSocketSession>> sessionMap = new HashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //在websocket连接建立成功后，被自动调用
        System.out.println("TestWebSocket连接成功");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String json = message.getPayload();
        JSONObject jsonObject = new JSONObject(json);
        String userid =jsonObject.getString("userid");
        String state =jsonObject.getString("state");
        String type =jsonObject.getString("type");
        Map<String,String> map = new HashMap<>();
        map.put("userid",userid);
        map.put("type",type);
        userMap.put(session,map);
        ReturnValue returnValue = new ReturnValue();
        Room room = roomService.getRoomByUserId(Integer.valueOf(userid));

        //  判定当前用户是否已经进入房间. (拿着房间管理器进行查询)
        if(room ==null){
            returnValue.isFail("用户未匹配到房间");
            session.sendMessage(new TextMessage(returnValue.toJson()));
            session.close();
            return;
        }

        if("0".equals(state)){
            //  判定当前是不是多开 (该用户是不是已经在其他地方进入游戏了)
            if (wuZiQiService.getgamePlayerSession(Integer.valueOf(userid)) != null) {
                returnValue.isFail("禁止多开游戏页面");
                session.sendMessage(new TextMessage(returnValue.toJson()));
                return;
            }

            //  设置当前玩家上线!
            wuZiQiService.gamePlayerEntry(Integer.valueOf(userid), session);

            UserGameInfo ugi = new UserGameInfo();
            User user = new User();
            user.setUser_id(Integer.parseInt(userid));
            ugi.setUser(user);
            ugi.setType(type);
            List<UserGameInfo> ugiList = wuZiQiService.getUserGameInfo(ugi);
            if(ugiList.size() == 0){
                returnValue.isFail("未找到匹配用户");
                session.sendMessage(new TextMessage(returnValue.toJson()));
                session.close();
                return;
            }
            UserGameInfo ugiInfo = ugiList.get(0);
            synchronized (room) {
                if (room.getPlayers() == null) {
                    // 第一个玩家还尚未加入房间.
                    // 就把当前连上 websocket 的玩家作为 user1, 加入到房间中.
                    List<UserGameInfo> lists = new ArrayList<>();
                    lists.add(ugiInfo);
                    room.setPlayers(lists);
                    System.out.println("玩家 " + ugiInfo.getUser().getUser_name() + " 已经准备就绪! 作为玩家1");
                    returnValue.setRetDesc1(room.getRoom_id());
                    returnValue.isSuccess("进入房间");
                    session.sendMessage(new TextMessage(returnValue.toJson()));
                    return;
                }
                if (room.getPlayers().size() == 1) {
                    List<UserGameInfo> lists = room.getPlayers();
                    lists.add(ugiInfo);
                    room.setPlayers(lists);
                    System.out.println("玩家 " + ugiInfo.getUser().getUser_name() + " 已经准备就绪! 作为玩家2");
                    returnValue.setRetDesc1(room.getRoom_id());
                    returnValue.isSuccess("进入房间");
                    session.sendMessage(new TextMessage(returnValue.toJson()));

                    // 当两个玩家都加入成功之后, 就要让服务器, 给这两个玩家都返回 websocket 的响应数据.
                    // 通知这两个玩家说, 游戏双方都已经准备好了.
                    noticeGameReady(room, String.valueOf(room.getPlayers().get(0).getUser().getUser_id()));
                    noticeGameReady(room, userid);
                    String userids = "";
                    for(UserGameInfo ugit:lists){
                        userids += (ugit.getUser().getUser_id()) + "-";
                    }
                    room.setState("1");
                    room.setUser_ids(userids);
                    wuZiQiService.updateGameInfo(room);
                    return;
                }

            }

            //  此处如果又有玩家尝试连接同一个房间, 就提示报错.
            //    这种情况理论上是不存在的, 为了让程序更加的健壮, 还是做一个判定和提示.
            returnValue.isFail("当前房间已满, 您不能加入房间");
            session.sendMessage(new TextMessage(returnValue.toJson()));
        }
    }


    private void noticeGameReady(Room room,String userid) throws IOException {
        ReturnValue returnValue = new ReturnValue();
        returnValue.isSuccess("对局开始");
        returnValue.setRetList(room.getPlayers());
        WebSocketSession session= wuZiQiService.getgamePlayerSession(Integer.valueOf(userid));
        session.sendMessage(new TextMessage(returnValue.toJson()));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //连接出现异常的时候，被自动调用
        System.out.println("TestWebSocket连接异常");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Map<String,String> map = userMap.remove(session);
        if(map != null){
            String userid = map.get("userid");
            String type = map.get("type");
            wuZiQiService.gamePlayerOut(Integer.valueOf(userid));
        }
        System.out.println("TestWebSocket关闭连接");
    }

}
